package com.springcloud.controller;

import com.springcloud.EventBody;
import com.springcloud.configuration.MyEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 顾志杰
 */
@RestController
@RequestMapping("bus")
@Slf4j
public class MyEventContrellor {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private ApplicationContext applicationContext;

    @PostMapping("publish/myevent")
    public boolean publishMyEvent(@RequestBody EventBody body) {
        MyEvent event = new MyEvent(body, applicationContext.getId(), "");
        try {
            // 可以注入ApplicationEventPublisher来发送event
            eventPublisher.publishEvent(event);
            // 也可以直接使用
            // applicationContext.publishEvent(event)
            return true;
        } catch (Exception e) {
            log.error("failed in publishing event", e);
        }
        return false;
    }
}
